const fs = require('fs');
const path = require('path');

// 配置需要修改的文件和规则
const modifications = [
  {
    type: 'replaceText',
    filePath: path.resolve(__dirname, '../../craco.config.js'),
    target:
      "// const { addLoadersForWorkersAndPackages } = require('../craco-common');",
    replacement:
      "const { addLoadersForWorkersAndPackages } = require('../craco-common');",
  },
  {
    type: 'replaceText',
    filePath: path.resolve(__dirname, '../../craco.config.js'),
    target: '// addLoadersForWorkersAndPackages(webpackConfig);',
    replacement: 'addLoadersForWorkersAndPackages(webpackConfig);',
  },
  {
    type: 'replaceText',
    filePath: path.resolve(__dirname, '../../tsconfig.json'),
    target: '"rootDir": "src",',
    replacement: '"rootDir": "../../",',
  },
  {
    type: 'replaceText',
    filePath: path.resolve(__dirname, '../../tsconfig.json'),
    target: '"src/**/*.json"',
    replacement: '"src/**/*.json",\n    "../../commons"',
  },
  {
    type: 'modifyJSON',
    filePath: path.resolve(__dirname, '../../package.json'),
    keyPath: ['dependencies', '@amcax/base'],
    newValue: '*',
  },
  {
    type: 'modifyJSON',
    filePath: path.resolve(__dirname, '../../package.json'),
    keyPath: ['dependencies', '@amcax/renderer'],
    newValue: '*',
  },
];

// 处理普通代码替换
function replaceText(data, target, replacement) {
  if (!data.includes(target)) {
    console.log(`未找到目标代码，无需替换：${target}`);
    return data;
  }
  return data.replace(target, replacement);
}

// 处理 JSON 字段修改
function modifyJSON(data, keyPath, newValue) {
  let current = data;
  for (let i = 0; i < keyPath.length - 1; i++) {
    const key = keyPath[i];
    if (!(key in current)) {
      console.error(`路径 ${keyPath.join('.')} 中的 ${key} 不存在`);
      return null;
    }
    current = current[key];
  }
  const lastKey = keyPath[keyPath.length - 1];
  if (!(lastKey in current)) {
    console.error(`路径 ${keyPath.join('.')} 中的 ${lastKey} 不存在`);
    return null;
  }
  current[lastKey] = newValue;
  return data;
}

// 主处理逻辑
function processModifications(modifications) {
  const fileGroupedModifications = modifications.reduce((acc, mod) => {
    if (!acc[mod.filePath]) acc[mod.filePath] = [];
    acc[mod.filePath].push(mod);
    return acc;
  }, {});

  Object.entries(fileGroupedModifications).forEach(([filePath, operations]) => {
    fs.readFile(filePath, 'utf8', (err, rawData) => {
      if (err) {
        console.error(`读取文件失败：${filePath}`, err);
        return;
      }

      let updatedData = rawData;
      let isJSON = false;

      // 尝试解析为 JSON，如果失败则按文本处理
      let jsonData;
      try {
        jsonData = JSON.parse(rawData);
        isJSON = true;
      } catch {
        jsonData = null;
      }

      if (isJSON) {
        // 针对 JSON 文件的所有修改
        operations.forEach(({ type, keyPath, newValue }) => {
          if (type === 'modifyJSON') {
            jsonData = modifyJSON(jsonData, keyPath, newValue);
          }
        });

        // 写回 JSON 文件
        fs.writeFile(
          filePath,
          JSON.stringify(jsonData, null, 2),
          'utf8',
          (err) => {
            if (err) {
              console.error(`写入文件失败：${filePath}`, err);
            } else {
              console.log(`JSON 文件更新成功：${filePath}`);
            }
          },
        );
      } else {
        // 针对普通文本文件的所有替换
        operations.forEach(({ type, target, replacement }) => {
          if (type === 'replaceText') {
            updatedData = replaceText(updatedData, target, replacement);
          }
        });

        // 写回文本文件
        fs.writeFile(filePath, updatedData, 'utf8', (err) => {
          if (err) {
            console.error(`写入文件失败：${filePath}`, err);
          } else {
            console.log(`文本文件更新成功：${filePath}`);
          }
        });
      }
    });
  });
}

// 执行所有修改
processModifications(modifications);
